import axios from 'axios'
import { message } from 'ant-design-vue'
import store from '@/store'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import storage from 'store'

axios.defaults.timeout = 120000
axios.defaults.headers['Content-Type'] = 'application/json'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
const key = 'popup'
// 响应拦截
axios.interceptors.response.use(response => {
  return response
}, error => {
  if (error.response) {
    switch (error.response.status) {
      case 400:
        message.error('参数错误')
        break
      case 403:
        message.error('跨域请求')
        break
      case 404:
        message.error('404 Not Found')
        break
      case 401:
          message.error({ content: error.response.data.message || '等待时间过长，请重新登录', key, duration: 2 })
        const selfLogin = (storage.get(USER_INFO) || {}).selfLogin
        store.dispatch('Logout').then(() => {
          if (process.env.NODE_ENV === 'production') {
            if (selfLogin) {
              setTimeout(() => {
                window.location.reload()
              }, 1500)
            } else {
              window.location.href = process.env.VUE_APP_API_BASE_URL.replace('9999', '8888') + '/splash/'
            }
          } else {
            setTimeout(() => {
              window.location.reload()
            }, 1500)
          }
        })
        break
      case 500:
        break
      default:
    }
    return error
  }
})

export default function Fetch ({ url, params = {}, method = 'GET', headers = {}, token = true, responseType = '' }) {
  return new Promise((resolve, reject) => {
    const options = {
      'method': method,
      'url': url,
      'headers': headers,
      'responseType': responseType
    }
    options[method === 'GET' ? 'params' : method === 'DELETE' ? 'params' : 'data'] = params
    const tokens = storage.get(ACCESS_TOKEN)
    token && (options.headers['X-Access-Token'] = tokens)
    const createAxios = function (options) {
      axios(options).then((response) => {
        // 暂时在这里进行封装如果code不等于200返回后台报错 lx 4.1
        // if (response.data.success !== true) {
        //   message.error(response.data.message)
        // }
        resolve(response.data)
      }).catch((error) => {
        reject(error.data)
      })
    }
    createAxios(options)
  })
}
